<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Sites extends Controller
{
    /**
     * @return Response_Response
     */
    private function getResponse()
    {
        $format = isset($_REQUEST['format'])? $_REQUEST['format'] : 'xml';

        if( $format === 'xml' )
            return new Response_XmlResponse();
        elseif( $format === 'json' )
            return new Response_JsonResponse();
        else
            throw new Exception(sprintf ('Unknown response format "%s"', $format));
    }

	public function action_index()
	{
		$logger = new Log_RequestLogger(DOCROOT.'logs/request');
        $logger->write();

        $response = $this->getResponse();
        $this->response->headers('Content-Type', $response->getContentType());

        $id = isset($_REQUEST['id'])? $_REQUEST['id'] : NULL;

        try
        {
            if( $id )
                $sites = ORM::factory('Site')->and_where('id', '=', $id)->find_all();
            else
                $sites = ORM::factory('Site')->find_all();
        }
        catch(Exception $e)
        {
            $this->response->body($response->getError(500, 'Server error'));
            return;
        }

        if( !$sites->count() )
        {
            $this->response->body($response->getError(404, 'Site not found'));
            return;
        }

        // TODO: Добавить кэширование массива либо всего xml
        $sites_arr = array();
        foreach($sites as $site)
        {
            $site_a = $site->as_array();
            $infos = $site->parse_infos->find_all();
            $site_a['parse_infos'] = array();
            foreach ($infos as $info)
            {
                $site_a['parse_infos'][] = $info->as_array();
            }
            $sites_arr[] = $site_a;
        }


        $this->response->body($response->getSites($sites_arr));
	}
}